package org.example.gateway.chain;

import org.example.gateway.cache.PluginCache;
import org.example.gateway.config.ServerConfigProperties;
import org.example.gateway.plugin.AbstractGatewayPlugin;
import org.example.gateway.plugin.GatewayPlugin;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

public class PluginChain extends AbstractGatewayPlugin {
    /**
     * pos指向当前插件
     */
    private int pos;
    /**
     * 插件链
     */
    private List<GatewayPlugin> plugins;

    private final String appName;

    public PluginChain(ServerConfigProperties properties, String appName) {
        super(properties);
        this.appName = appName;
    }

    /**
     * 将启用的插件添加到链中
     *
     * @param shipPlugin
     */
    public void addPlugin(GatewayPlugin shipPlugin) {
        if (plugins == null) {
            plugins = new ArrayList<>();
        }
        if (!PluginCache.isEnabled(appName, shipPlugin.name())) {
            return;
        }
        plugins.add(shipPlugin);
        //按插件顺序排序
        plugins.sort(Comparator.comparing(GatewayPlugin::order));
    }

    @Override
    public Integer order() {
        return null;
    }

    @Override
    public String name() {
        return null;
    }

    @Override
    public Mono<Void> execute(ServerWebExchange exchange, PluginChain chain) {
        if (pos == plugins.size()) {
            return exchange.getResponse().setComplete();
        }
        return chain.plugins.get(pos++).execute(exchange, chain);
    }

    public String getAppName() {
        return appName;
    }
}
